//
//  DefaultKeyboardEmojiPad.swift
//  Keyboard
//
//  Created by 周张林 on 17/8/12.
//  Copyright © 2017年 周张林. All rights reserved.
//

import UIKit

class EmojiEntity {
    var title:String!
    var emojis:[String]! = []
}

/// 表情
class DefaultKeyboardEmojiPad:UIView
{
    
    weak var inputController:UIInputViewController?
    weak var delegate:KeyboardDelegate?
    
    var peopleEmoji:EmojiEntity!
    var flowerEmoji:EmojiEntity!
    var bellEmoji:EmojiEntity!
    var vehicleEmoji:EmojiEntity!
    var numberEmoji:EmojiEntity!
    
    var scrollView:UIScrollView!
    var titleLabel:UILabel!
    var tabButtons:[UIButton]! = []
    
    var btnABC:UIButton!
    var btnDelete:UIButton!
    var btnReturn:UIButton!
    
    let tabs = ["number","vehicle","people","flower","bell"]
    let icon = ["①","⎈","♕","❀","☏"]
    
    var selectTabIndex = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clear
        parseJson();
        initView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func parseJson(){
        //解析emoji
        let path = Bundle.main.path(forResource: "emoji", ofType: "json")
        let url = URL.init(fileURLWithPath: path!)
        if let data = try? Data.init(contentsOf: url) {
            if let json = try? JSONSerialization.jsonObject(with: data, options:[]) as? [String:[String]] {
                
                for key in (json?.keys)! {
                    
                    let entity = EmojiEntity()
                    entity.emojis = json?[key]
                    entity.title = key
                    
                    if key == "number" {
                        numberEmoji = entity
                    }
                    else if key == "vehicle" {
                        vehicleEmoji = entity
                    }
                    else if key == "people" {
                        peopleEmoji = entity
                    }
                    else if key == "flower" {
                        flowerEmoji = entity
                    }
                    else if key == "bell" {
                        bellEmoji = entity
                    }
                }
            }
        }
    }
    
    func initView() -> Void {
        titleLabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
        titleLabel.textColor = UIColor.white
        titleLabel.isUserInteractionEnabled = false
        titleLabel.textAlignment = .center
        self.addSubview(titleLabel)
        
        scrollView = UIScrollView()
        scrollView.backgroundColor = UIColor.clear
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        self.addSubview(scrollView)
        
        //add tab
        for (i,_) in tabs.enumerated() {
            let btn = DefaultKeyboardBtn.newButton(title: icon[i], tag: i, kbDelegate: nil,fontSize:16)
            tabButtons.append(btn)
            self.addSubview(btn)
            btn.addTarget(self, action: #selector(onTabClick(_:)), for: .touchUpInside)
        }
        
        tabButtons[0].alpha = 0.7//selected
        titleLabel.text = tabs[0]
        
        btnABC = DefaultKeyboardBtn.newButton(title: "ABC", tag: 1, kbDelegate: self,fontSize:18)
        self.addSubview(btnABC)
        
        btnDelete = DefaultKeyboardBtn.newButton(title: "⌫", tag: 2, kbDelegate: self,fontSize:18)
        self.addSubview(btnDelete)
        
        btnReturn = DefaultKeyboardBtn.newButton(title: "↵", tag: 3, kbDelegate: self,fontSize:32)
        addSubview(btnReturn)
    }
    
    func showEmojiByName(_ name:String)->Void
    {
        //"number","vehicle","people","flower","bell"
        var arr:EmojiEntity!
        switch(name)
        {
        case tabs[0]:
            arr = numberEmoji
        case tabs[1]:
            arr = vehicleEmoji
        case tabs[2]:
            arr = peopleEmoji
        case tabs[3]:
            arr = flowerEmoji
        case tabs[4]:
            arr = bellEmoji
        default:break
        }
        while scrollView.subviews.count > 0 {
            scrollView.subviews[0].removeFromSuperview()
        }
        titleLabel.text = name
        var pageIndex:CGFloat = 0
        var i:CGFloat = 0
        var page:UIView!
        var currCol:CGFloat = 0
        var currRow:CGFloat = 0
        let size:CGFloat = 33 //* UIScreen.main.scale
        let pageWidth:CGFloat = frame.width-10
        let pageHeight:CGFloat = frame.height-85
        let COL:CGFloat = floor(pageWidth/size)
        var ROW:CGFloat = floor(pageHeight/(size+5)/UIScreen.main.scale) - 1
        if ROW <= 0 {
            ROW = floor(pageHeight/size)
        }
        for emoji in arr.emojis {
            if i == 0 && i < CGFloat(arr.emojis.count) {
                page = UIView()
                let x = 10 + CGFloat(pageIndex)*pageWidth
                page.frame = CGRect(x:x,y:0,width:pageWidth,height:pageHeight)
                scrollView.addSubview(page)
            }
            
            let btn = UIButton.init(type: .system)
            btn.frame = CGRect(x: currCol*size, y: currRow*size , width: size , height: size)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 28)
            btn.setTitle(emoji, for: .normal)
            btn.addTarget(self, action: #selector(onTapEmoji(_:)), for: .touchUpInside)
            page.addSubview(btn)
            
            currCol = currCol + 1
            if currCol == COL {
                currCol = 0
                
                currRow = currRow + 1
                if currRow == ROW {
                    currRow = 0
                    
                    i = 0
                    pageIndex = pageIndex + 1
                    
                    page = UIView()
                    let x = 10 + CGFloat(pageIndex)*pageWidth
                    page.frame = CGRect(x:x,y:0,width:pageWidth,height:pageHeight)
                    scrollView.addSubview(page)
                }
            }
            
            i = i + 1
        }
        scrollView.contentSize.width = pageWidth*(pageIndex+1)
    }
    
    override func layoutSubviews() -> Void {
        let margin:CGFloat = 5
        
        scrollView?.frame = CGRect(x:5,y:40,width:frame.width-10,height:frame.height-85)
        
        let minWidth = (frame.width - margin * CGFloat(tabButtons.count + 2) ) / CGFloat(tabButtons.count + 2)
        for i in 0..<tabButtons.count  {
            let btn = tabButtons[i]
            btn.frame = CGRect(x: margin + minWidth*CGFloat(i) , y: frame.height - 40 , width: minWidth-margin, height: 35 )
        }
        showEmojiByName( tabs[selectTabIndex] )
        
        btnABC?.frame = CGRect(x: margin, y: margin, width: 50, height: 30)
        btnDelete?.frame = CGRect(x: frame.width-frame.width/10-margin, y: margin, width: frame.width/10, height: 30)
        btnReturn?.frame = CGRect(x: frame.width-frame.width/7-margin, y: frame.height - 40 , width: frame.width/7, height: 35 )
        
        titleLabel?.frame.size.width = frame.width
    }
    
    func onTapEmoji(_ sender:UIButton)->Void
    {
        inputController?.textDocumentProxy.insertText((sender.titleLabel?.text)!)
    }
    
    func onTabClick(_ sender:UIButton)->Void{
        if selectTabIndex != sender.tag {
            selectTabIndex = sender.tag
            showEmojiByName(tabs[selectTabIndex] )
            scrollView.contentOffset.x = 0
            for btn in tabButtons {
                btn.alpha = 1
            }
            tabButtons[selectTabIndex].alpha = 0.7
        }
    }
    
    
    deinit {
        inputController = nil
        delegate = nil
        peopleEmoji = nil
        bellEmoji = nil
        vehicleEmoji = nil
        numberEmoji = nil
        flowerEmoji = nil
        
        scrollView = nil
        titleLabel = nil
        tabButtons = nil
        btnABC = nil
        btnDelete = nil
        btnReturn = nil
    }
}



extension DefaultKeyboardEmojiPad:DefaultKeyboardBtnDelegate{
    func didClick(_ sender:DefaultKeyboardBtn)->Void{
        switch sender.tag
        {
        case 1:
            delegate?.showWordPad()
        case 2:
            inputController?.textDocumentProxy.deleteBackward()
        case 3:
            inputController?.textDocumentProxy.insertText("\n")
        default:
            inputController?.textDocumentProxy.insertText((sender.titleLabel?.text)!)
        }
    }
}
